import { StyleSheet, View, FlatList } from 'react-native';
import React, { useState, useCallback } from 'react';
import { useFocusEffect } from '@react-navigation/native';
import { useTranslation } from 'react-i18next';
import { ContentStatus } from '~/components';
import { px2dp } from '~/utils/px2dp';
import { getUserCourseListApi } from '~/api/deviceApi';
import { observer } from '~/store';
import MyCourseItem from './MyCourseItem';

type Type = 'remote' | 'normal';
interface Props {
    type: Type;
    subDevice_sn: string;
    pupillus_mobile: string;
    device_sn: string;
    tableIndex: number;
}
const MyCourse = observer((props: Props) => {
    const { t } = useTranslation();
    const { type, subDevice_sn, pupillus_mobile, device_sn, tableIndex } = props;
    const [listData, setListData] = useState([]);
    const [isRefreshing, setIsRefreshing] = useState(false); // 是否刷新
    const [allStatus, setAllStatus] = useState(2);
    const getData = async () => {
        var base = false;
        try {
            const res = await getUserCourseListApi({
                mobile: pupillus_mobile || '',
                device_sn: subDevice_sn,
            });
            setIsRefreshing(false);
            if (res.status == 1) {
                var courseArrayUI: any = [];
                var allStatus = 2;
                var courseId = '';
                var user_course_id = '';
                if (res.course_list.length > 0) {
                    res.course_list.forEach(function (v, index) {
                        if (v.course_status == 1) {
                            (courseId = v.course_id), (user_course_id = v.id);
                        }
                        var _remainingDays = v.remaining_days ? parseInt(v.remaining_days) : 0;
                        _remainingDays = _remainingDays + (v.add_day ? parseInt(v.add_day) : 0);
                        var courseStatus = v.course_status;
                        var course = {
                            course: index,
                            useState: courseStatus,
                            course_title_id: v.course_title_id,
                            use_day: v.use_day,
                            courseName: v.course_name,
                            type: v.type,
                            remainingDays: _remainingDays,
                            courseid: v.course_id,
                            id: v.id,
                            course_img: v.course_img,
                            stage: v.stage ? v.stage : null,
                            title_tip: v.title_tip,
                            en_course_name: v.en_course_name,
                        };

                        courseArrayUI.push(course);
                    });
                } else {
                    base = true;
                    res.base_course.list?.forEach(function (v, index) {
                        if (v.course_status == 1) {
                            (courseId = v.course_id), (user_course_id = v.id);
                        }
                        var courseStatus = v.course_status;
                        var course = {
                            course: index,
                            useState: courseStatus,
                            courseName: v.course_name,
                            en_course_name: v.en_course_name,
                            remainingDays: 0,
                            courseid: v.course_id,
                            id: v.id,
                            course_img: v.course_img,
                            stage: v.stage ? v.stage : null,
                            use_day: v.use_day,
                            title_tip: v.title_tip,
                        };
                        courseArrayUI.push(course);
                    });
                }

                for (var i = 0; i < courseArrayUI.length; i++) {
                    if (courseArrayUI[i].useState == 1) {
                        allStatus = 1;
                    }
                }
                const newArray: any = arrSpace(res.base_course, courseArrayUI);
                try {
                    const updatedArray = newArray.map((item) => {
                        const typeZeroData = item.list.filter((dataItem) => dataItem.type == '0');
                        const totalDays =
                            typeZeroData.length > 0
                                ? typeZeroData.reduce((sum, dataItem) => sum + dataItem.remainingDays, 0)
                                : item.total_day;
                        return {
                            ...item,
                            total_day: totalDays,
                        };
                    });
                    setListData(updatedArray || []);
                } catch (error) {}
                setAllStatus(allStatus);
            }
        } catch (error) {
            setIsRefreshing(false);
        }
    };

    const arrSpace = (arr1, arr2) => {
        let expertList = {
            name: t('MyCourse.t2'),
            num: 0,
            id: '0',
            total_day: 0,
            list: [],
            use_day: 0,
            add_time: '',
            base_course_icon: '',
            base_course_img: '',
            device_id: '',
            status: '0',
            title_img: '',
            en_name: t('MyCourse.t2'),
        };

        let arr_list = [expertList];
        arr1?.forEach((item) => {
            expertList = {
                en_name: item.en_name,
                name: item.name,
                id: item.id,
                add_time: item.add_time,
                base_course_icon: item.base_course_icon,
                base_course_img: item.base_course_img,
                device_id: item.device_id,
                num: item.num,
                status: item.status,
                total_day: item.total_day,
                use_day: item.use_day,
                list: [],
                title_img: item.title_img,
            };
            arr_list.push(expertList);
        });
        arr_list.forEach((v: any) => {
            arr2.forEach((j, i) => {
                if (v.id == j.course_title_id) {
                    v.list.push(j);
                }
            });
        });
        return arr_list;
    };

    const handleRefresh = () => {
        getData();
        setIsRefreshing(true);
    };

    useFocusEffect(
        useCallback(() => {
            getData();
        }, [tableIndex]),
    );

    const renderItem = ({ item }) => {
        return (
            <View>
                {item?.list.length > 0 && (
                    <MyCourseItem
                        type={type}
                        allStatus={allStatus}
                        device_sn={device_sn}
                        subDevice_sn={subDevice_sn}
                        pupillus_mobile={pupillus_mobile}
                        course={item}
                        onRefresh={getData}
                    />
                )}
            </View>
        );
    };
    return (
        <View style={styles.container}>
            <FlatList
                contentContainerStyle={styles.contentContainerStyle}
                showsVerticalScrollIndicator={false}
                data={listData}
                renderItem={renderItem}
                keyExtractor={(item, index) => index.toString()}
                onEndReachedThreshold={0.1}
                onRefresh={handleRefresh}
                refreshing={isRefreshing}
                ListEmptyComponent={() => <ContentStatus status="empty" source={{ title: t('MyCourse.t1') }} />}
            />
        </View>
    );
});

export default MyCourse;

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },

    contentContainerStyle: {
        flexGrow: 1,
        paddingBottom: '20%',
        marginHorizontal: px2dp(24),
    },
});
